package HomeWork20241201;

import java.util.Random;
/*冒泡排序*/

public class HomeWork2 {
    public static void main(String[] args) {
        int[] arr = getArr();

        System.out.print("排序前:");
        printArr(arr);

        maoPaoSort(arr);
        System.out.print("\n排序后:");
        printArr(arr);
    }


    /**
     * 冒泡排序
     *
     * @param arr
     */
    public static void maoPaoSort(int[] arr) {
        boolean flag;
        for (int i = 0; i < arr.length - 1; i++) {
            flag = false;
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                    flag = true;
                }
            }
            if (!flag) {
                break;
            }
        }
    }

    /**
     * 打印数组
     *
     * @param arr
     */
    public static void printArr(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }

    /**
     * 随机生成数组
     *
     * @return 返回数组
     */
    public static int[] getArr() {
        int arr[] = new int[10];

        Random r = new Random();

        for (int i = 0; i < arr.length; i++) {
            int rNum = r.nextInt(100);
            arr[i] = rNum;
        }
        return arr;
    }
}
